import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'dart:convert';

import '../servie/service_method.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; //屏幕适配方案
import 'package:flutter_easyrefresh/easy_refresh.dart'; //上拉加载 下拉刷新
import 'package:transparent_image/transparent_image.dart'; //图片占位图
import 'package:fluttertoast/fluttertoast.dart';

import '../model/category.dart'; //数据模型
import '../provide/child_category.dart'; //状态管理 子分类provide
import '../provide/good_list.dart'; //状态管理 分类商品provide
import 'package:provide/provide.dart';//状态管理库


import '../routers/application.dart';
import 'package:fluro/fluro.dart';

//页面
class CategoryPage extends StatefulWidget {
  CategoryPage({Key key}) : super(key: key);

  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {

  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("商品分类"),
        centerTitle: true,
      ),
      body: Container(
        child:Row(
          children: <Widget>[
            LeftCategory(),
            Column(
              children: <Widget>[
                  RightCategoryNavState(),
                  GetCategoryGoodList()
              ],
            )
          ],
        )
      ),
    );
  }
}

//左侧大类导航
class LeftCategory extends StatefulWidget {
  LeftCategory({Key key}) : super(key: key);
  _LeftCategoryState createState() => _LeftCategoryState();
}

class _LeftCategoryState extends State<LeftCategory> {

  List<CategoryBigModel> list =new List();
  var listIndex = 0;

  @override
  void initState() {
    this._getCategory();
    this._getGoodsList();
    super.initState();
  }
  //分类数据请求
  void _getCategory() async{
    print('加载分类数据');
    await requset('getCategory').then((val){
      var data = json.decode(val.toString());
      CategoryBigListModel listdata =  CategoryBigListModel.fromJsonLsit((data['data'] as List).cast());
      setState(() {
        list = listdata.data;
      });
      var childList = (listdata.data[0].bxMallSubDto).map((e){
         return BxMallSubDto.fromJons(e);
      }).toList();
      //设置初始化的子分类
      Provide.value<ChildCategory>(context).getChildCategory(
          childList,//大类下的子分类集合
          childList[0].mallCategoryId//大类的id
      );
    });
  }
  //请求商品接口 categoryId(大类)
  void _getGoodsList({String categoryId }) async {
    var formData = {
      'categoryId':categoryId==null ? '4' : categoryId,
      'categorySubId':'',
      'page':1
    };
    await requset('getMallGoods',formData:formData).then((val){
      var data = json.decode(val.toString());
      setState(() {
        var listgoods = CategoryGoodListModel.fromJsonLsit((data['data'] as List).cast()).data;
        Provide.value<CategoryGoodsListProvide>(context).getGoodsList(listgoods);
      });
    });
  }
  //每项分类
  Widget _leftInkWell(index){
    bool isChilck = index==listIndex ? true : false ;
    return InkWell(
      onTap: (){
        //设置当前分类的索引

        var childList = (list[index].bxMallSubDto).map((e){
         return BxMallSubDto.fromJons(e);
        }).toList();
        //设置当前分类的子分类
        Provide.value<ChildCategory>(context).getChildCategory(
          childList,//子分类的集合
          list[index].mallCategoryId//当前分类的id
        );
        //请求商品数据
        _getGoodsList(categoryId:list[index].mallCategoryId);

        setState(() {
          listIndex = index;
        });
      },
      child:Container(
        height: ScreenUtil().setHeight(100.0),
        padding: EdgeInsets.only(left: 10.0,top:20.0),
        decoration: BoxDecoration(
          color:isChilck ? Color.fromRGBO(236, 236, 236, 1.0) : Colors.white,
          border: Border(bottom: BorderSide(color: Colors.black12,width: 1))
        ),
        child: Text(list[index].mallCategoryName,style: TextStyle(fontSize: ScreenUtil().setSp(28.0))),
      ) ,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
       width: ScreenUtil().setWidth(180),
       decoration: BoxDecoration(
         border: Border(right: BorderSide(width: 1,color: Colors.black12))
       ),
       child:ListView.builder(
         itemCount:list.length,
         itemBuilder: (context,index){
           return _leftInkWell(index);
         },
       ),
    );
  }
}
// //右侧子导航
class RightCategoryNavState extends StatefulWidget {
  RightCategoryNavState({Key key}) : super(key: key);

  _RightCategoryNavStateState createState() => _RightCategoryNavStateState();
}

class _RightCategoryNavStateState extends State<RightCategoryNavState> {

  //请求商品接口 categoryId(大类) categorySubId（子类） page（页数）
  void _getGoodsList(categorySubId) async {
    var formData = {
      'categoryId':Provide.value<ChildCategory>(context).categoryId,
      'categorySubId':categorySubId,
      'page':1
    };
    await requset('getMallGoods',formData:formData).then((val){
      var data = json.decode(val.toString());
      setState(() {
        if(data['data']==null){
          Provide.value<CategoryGoodsListProvide>(context).getGoodsList([]);
        } else {
          var listgoods = CategoryGoodListModel.fromJsonLsit((data['data'] as List).cast()).data;
          Provide.value<CategoryGoodsListProvide>(context).getGoodsList(listgoods);
        }
      });
    });
  }
  //每个子nav
  Widget _itemInkwellnav(BxMallSubDto item,int index){
    bool isClick = false;
    isClick = (index==Provide.value<ChildCategory>(context).childIndex) ? true :false ;
    return InkWell(
      onTap: (){
        Provide.value<ChildCategory>(context).changeChildIndex(index,item.mallSubId);
        //请求子类的商品数据
        _getGoodsList(item.mallSubId);
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
        child: Text(item.mallSubName,style: TextStyle(
          fontSize: ScreenUtil().setSp(28.0),
          color: isClick ? Colors.pink :Colors.black87
        ),),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Provide<ChildCategory>(
      builder:(context,child,childCategorystate){
        return Container(
          height: ScreenUtil().setHeight(80.0),
          width: ScreenUtil().setWidth(570.0),
          decoration: BoxDecoration(
            color:Colors.white,
            border: Border(bottom: BorderSide(color:Colors.black12,width: 1.0))
          ),
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount:childCategorystate.childcategoryList.length,
            itemBuilder: (context,index){
              return _itemInkwellnav(childCategorystate.childcategoryList[index],index);
            },
          ),
        );
      }
    );

  }
}

//分类商品列表
class GetCategoryGoodList extends StatefulWidget {
  GetCategoryGoodList({Key key}) : super(key: key);

  _GetCategoryGoodListState createState() => _GetCategoryGoodListState();
}

class _GetCategoryGoodListState extends State<GetCategoryGoodList> {
  GlobalKey<EasyRefreshState> _easyRefreshKey =new GlobalKey<EasyRefreshState>();
  GlobalKey<RefreshFooterState> _footerkey = new GlobalKey<RefreshFooterState>();
  var scorllController = new ScrollController(); //滚动的控制器
  //请求更多数据接口
  void _getMoreGoodsList() async {
    Provide.value<ChildCategory>(context).addpage();
    Provide.value<ChildCategory>(context).changeNoMore('加载成功');
    var formData = {
      'categoryId':Provide.value<ChildCategory>(context).categoryId,
      'categorySubId':Provide.value<ChildCategory>(context).subId,
      'page':Provide.value<ChildCategory>(context).page
    };
    await requset('getMallGoods',formData:formData).then((val){
      var data = json.decode(val.toString());
      setState(() {
        if(data['data']==null){
          //Provide.value<CategoryGoodsListProvide>(context).getGoodsList([]);
          Provide.value<ChildCategory>(context).changeNoMore('没有更多了');
          Fluttertoast.showToast(
            msg: "已经到底了",
            toastLength: Toast.LENGTH_SHORT, //短提示
            gravity: ToastGravity.CENTER,//居中提示
            backgroundColor: Colors.pink,
            textColor: Colors.white,
            timeInSecForIos: 1,
            fontSize: 16.0
          );
        } else {
          var listgoods = CategoryGoodListModel.fromJsonLsit((data['data'] as List).cast()).data;
          Provide.value<CategoryGoodsListProvide>(context).addGoodsList(listgoods);
        }
      });
    });
  }
  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
   return Provide<CategoryGoodsListProvide>(
      builder: (context,child,categoryGoodsListProvide){
          try {
            if(Provide.value<ChildCategory>(context).page==1){
              //切换类了滚动切换到顶部
              scorllController.jumpTo(0.0);
            }
          } catch (e) {
            print('进入页面第一次初始化:e');
          }
          if(categoryGoodsListProvide.goodsList.length > 0 ){
            return Expanded(
              child:  Container(
                  width: ScreenUtil().setWidth(570),
                  child:EasyRefresh(
                    key: _easyRefreshKey,
                    refreshFooter: ClassicsFooter(
                        key:_footerkey,
                        loadText:'上拉加载更多',// 提示加载文字
                        loadReadyText: '松手加载更多', // 准备加载文字
                        loadingText:'加载中...',// 正在加载文字
                        noMoreText: Provide.value<ChildCategory>(context).noMoreText, //没有数据时的显示
                        loadedText:'',//刷新完成文字
                        moreInfo: '加载中...',//更多信息文字颜色
                        bgColor: Colors.white,//背景颜色
                        textColor: Colors.pink,//字体颜色
                        moreInfoColor: Colors.pink,
                        showMore: false,//显示额外信息默认为时间
                    ),
                    child:ListView.builder(
                        controller:scorllController ,//控制器
                        itemCount: categoryGoodsListProvide.goodsList.length,
                        itemBuilder: (context,index){
                          return _listitemWidget(categoryGoodsListProvide.goodsList[index]);
                        },
                    ),
                    loadMore: () async {
                       print('上拉加载更多..');
                      _getMoreGoodsList();
                    },
                )
              ),
              );
          }else{
            return Expanded(
              child:  Center(
                 child: Text('暂无数据哦~~~'),
              ),
            );
          }
        },
    );
  }
  //商品图片widget
  Widget _goodsImage(CategoryGoodItemModel item){
    return Container(
      width:ScreenUtil().setWidth(200),
      child: FadeInImage.memoryNetwork(
          placeholder: kTransparentImage,
          image:item.image,
       ),
    );
  }
  //商品名称
  Widget _goodsName(CategoryGoodItemModel item){
    return Container(
      width: ScreenUtil().setWidth(370.0),
      padding: EdgeInsets.all(5.0),
      child: Text(item.goodsName,
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        fontSize: ScreenUtil().setSp(28.0),
        color: Colors.black12
      ),),
    );
  }
  //商品价格
  Widget _goodsPrice(CategoryGoodItemModel item){
    return Container(
      width: ScreenUtil().setWidth(370.0),
      margin: EdgeInsets.only(top:20.0),
      child: Row(
        children: <Widget>[
          Text('价格:￥${item.presentPrice}',style: TextStyle(color:Colors.pink,fontSize: ScreenUtil().setSp(30.0))),
          Text('￥${item.oriPrice}',style: TextStyle(color:Colors.black26,decoration: TextDecoration.lineThrough),),
        ],
      ),
    );
  }
  //商品组合
  Widget _listitemWidget(CategoryGoodItemModel item){
    return InkWell(
      onTap: (){
        Application.router.navigateTo(context,"/detail?id=${item.goodsId}",transition:TransitionType.inFromRight,transitionDuration:const Duration(milliseconds: 150));
      },
      child: Container(
       width: ScreenUtil().setWidth(570),
       padding: EdgeInsets.only(top:5.0,bottom: 5.0),
       decoration: BoxDecoration(
         color: Colors.white,
         border: Border(
           bottom: BorderSide(
             width: 0.5,
             color: Colors.black12
           )
         )
       ),
       child: Row(
         children: <Widget>[
           _goodsImage(item),
           Column(
             children: <Widget>[
               _goodsName(item),
               _goodsPrice(item)
             ],
           )
         ],
       ),
      ),
    );
  }
}

